package com.koron.css2.contractmanage.impl;

import com.koron.css2.ExportWordInterface;
import com.koron.css2.contractmanage.Enum.ContractTypeEnum;
import com.koron.css2.contractmanage.bean.ContractFileBean;
import com.koron.css2.contractmanage.bean.ContractManageBean;
import com.koron.css2.contractmanage.exception.ContractException;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.secret.StaticInfo;
import com.koron.util.secret.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.http.*;
import org.swan.bean.MessageBean;

import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 合同预览
 *
 */
public class ContractPreview implements ExportWordInterface {

    @Override
    public HttpEntity<?> exportWord(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            ContractManageBean queryBean = JsonUtils.objectToPojo(req.getData(), ContractManageBean.class);
            checkContractManageBean(userInfo.getCurWaterCode(), queryBean.getUserNo(), queryBean.getProjectId(), queryBean.getContractNo(), queryBean.getContractType());

            Map<String, Object> map = new HashMap<>();
            map.put("groupCode", userInfo.getCurWaterCode());
            map.put("userNo", queryBean.getUserNo());
            map.put("contractNo", queryBean.getContractNo());
            map.put("contractType", queryBean.getContractType());
            map.put("type", "css");
            map.put("contractContent", JsonUtils.objectToJson(queryBean));
            MessageBean mb = Tools.callMgInterface(StaticInfo.contractUrl + "/contract/contractDownload", map);
            if (mb.getCode() != Constant.MESSAGE_INT_SUCCESS) {
                MessageBean<Object> messageBean = MessageBean.create(Constant.MESSAGE_INT_FAIL, "调用获取合同文件接口失败! " + mb.getDescription(), null);
                return new ResponseEntity(messageBean, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            ContractFileBean contractFileBean = JsonUtils.objectToPojoIgnoreNone(mb.getData(), ContractFileBean.class);
            String fileName = contractFileBean.getFileName();
            String prefix = fileName.substring(0, fileName.lastIndexOf("."));
            String suffix = fileName.substring(fileName.lastIndexOf("."));

            byte[] bytes = Base64.getDecoder().decode(contractFileBean.getBase64File());
            HttpHeaders header = new HttpHeaders();
            String prefixName= URLEncoder.encode(prefix,"UTF-8");
            header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            header.setContentDispositionFormData("attachment", prefixName + suffix);
            return new ResponseEntity<byte[]>(bytes, header, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("合同预览失败: " + e.getMessage(), e);
            e.printStackTrace();
            MessageBean<Object> messageBean = MessageBean.create(Constant.MESSAGE_INT_FAIL, "合同预览失败: " + e.getMessage(), null);
            ResponseEntity responseEntity = new ResponseEntity(messageBean, HttpStatus.INTERNAL_SERVER_ERROR);
            return responseEntity;
        }
    }
    /**
     * 校验合同字段
     *
     * @param curWaterCode
     * @param userNo
     * @param projectId
     * @param contractType
     * @return
     */
    public void checkContractManageBean(String curWaterCode, String userNo, String projectId, String contractNo, String contractType) {
        if (StringUtils.isBlank(curWaterCode)) {
            throw new ContractException("当前用户未绑定水司！");
        }
        if (StringUtils.isBlank(projectId)) {
            throw new ContractException("参数中的报装ID不能为空！");
        }
        if (StringUtils.isBlank(userNo)) {
            throw new ContractException("参数中的户号不能为空！");
        }
        if (StringUtils.isBlank(contractNo)) {
            throw new ContractException("参数中的合同编号不能为空！");
        }
        if (StringUtils.isBlank(contractType)) {
            throw new ContractException("参数中的合同类型不能为空！");
        }
        if (StringUtils.isNotBlank(projectId)) {
            if (!ContractTypeEnum.CONTRACT_TYPE_2.getContractType().equals(contractType)) {
                if (!ContractTypeEnum.CONTRACT_TYPE_3.getContractType().equals(contractType)) {
                    throw new ContractException("参数中的合同类型不属于施工合同的类型！");
                }
            }
        }
    }

}
